package com.qf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.entity.TbSpeedkill;
import com.qf.mapper.SpeedkillMapper;
import com.qf.service.SpeedkillService;
import com.qf.util.*;
import com.qianfeng.util.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SpeedkillServiceImpl extends ServiceImpl<SpeedkillMapper, TbSpeedkill>implements SpeedkillService {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ResultMsg showdateMenu() {
        List<Date> dateMenus = DateUtil.getDateMenus();
        return ResultMsg.success(dateMenus);
    }

    @Override
    public ResultMsg showGoods(TbSpeedkill speedkill) {
        //redis中获得已经缓存过的数据
        List values = redisTemplate.opsForHash().values(RedisKey.SPEED_KILL_GOODS + DateUtil.date2Str(speedkill.getSpeedStarttime()));
        return ResultMsg.success(values);
    }

    @Override
    public ResultMsg speedkill(TbSpeedkill speedkill) {
        //redis中查 RedisKey.SPEED_KILL_GOODS+起始时间段---gid--秒杀商品
        String starttime=DateUtil.date2Str(speedkill.getSpeedStarttime());
        Object o = redisTemplate.opsForHash().get(RedisKey.SPEED_KILL_GOODS + starttime, speedkill.getGoodsId().toString());
        TbSpeedkill tbSpeedkill = JsonSerialize.toObject(o, TbSpeedkill.class);
        //是否有足够数量
        if(tbSpeedkill.getSpeedNum()<=0)
            return ResultMsg.faild(777,"数量不足，抢购失败");
        //更改秒杀的数量-1
        tbSpeedkill.setSpeedNum(tbSpeedkill.getSpeedNum()-1);
        redisTemplate.opsForHash().put(RedisKey.SPEED_KILL_GOODS + starttime, speedkill.getGoodsId().toString(),tbSpeedkill);
        //RedisKey.SPEED_KILL_GOODS_STOCk+gid
        //更改库存数量-1
        redisTemplate.boundValueOps(RedisKey.SPEED_KILL_GOODSSTOCK+tbSpeedkill.getGoodsId().toString()).decrement();
        return ResultMsg.success();
    }
}
